<?php


namespace App\Services;

use antcloud\AntCloudSDKCore\AddressClient;
use antcloud\AntCloudSDKCore\AntCloudClient;
use App\Models\Goods;
use App\Models\Order;
use App\Models\OrderLease;
use App\Models\ShopUser;
use App\Models\ZlbNotoryTask;


class ZlbService
{
    const LEASE_LIMIT_DAY = 7;//账单支付宽限期天数

    //租金归还状态，1足额归还，2部分归还，3未归还，4退租，5该订单整个生命周期已完结
    const LEASE_RENT_STATUS_YES = 1;
    const LEASE_RENT_STATUS_PART_YES = 2;
    const LEASE_RENT_STATUS_NOT = 3;
    const LEASE_RENT_STATUS_RENT_REFUND = 4;
    const LEASE_RENT_STATUS_END = 5;


    const STATUS_YES = 1;//成功
    const STATUS_NOT = 0;//失败

    const PRODUCT_METHOD =  'twc.notary.lease.biz.create';//产品方法
    const PRODUCT_QUERY_METHOD =  'twc.notary.lease.biz.query';//产品租赁平台查询接口方法
    const FILE_METHOD =  'twc.notary.lease.biznotary.create';//文件存证方法
    const REGINON_NAME =  'CN-HANGZHOU-FINANCE';
    const VERSION_NO =  '1.0';//版本

    const API_TYPE_USER = 'user';//租赁订单⽤户信息
    const API_TYPE_PRODUCT = 'product';//租赁宝商品信息
    const API_TYPE_ORDER = 'order';//租赁宝商品信息
    const API_TYPE_ORDER_PRODUCT = 'orderProduct';//租赁宝商品信息
    const API_TYPE_ORDER_LOGISTIC = 'logistic';//租赁宝物流信息
    const API_TYPE_ORDER_LEASE_PROMISE = 'leasePromise';//租赁订单承诺信息
    const API_TYPE_ORDER_RENTAL = 'rental';//租赁订单承诺信息
    const API_TYPE_INSURANCE = 'insurance';//订单投保
    //行业分类
    const DEFAULT_CATEGORY_CLASS = 'general_other';//默认行业

    const categoryList = [
        //3C办公
        '3c_mobile' =>'3C办公-手机',
        '3c_pc'=>'3C办公-电脑',
        '3c_camera'=>'3C办公-摄影',
        '3c_office'=>'3C办公-办公设备',
        '3c_other'=>'3C办公-3C其他',
        //IOT
        'iot_auto_container'=>'IOT-售卖柜',
        'iot_stage'=>'IOT-驿站',
        'iot_other'=>'IOT-其他',
        //新能源
        'ne_battery'=>'新能源-电池',
        'ne_electric_car'=>'新能源-电动车',
        'ne_other'=>'新能源-其他',
        //泛行业
        'general_furniture'=>'泛行业-家具',
        'general_tv'=>'泛行业-家电',
        'general_other'=>'泛行业-其他',
    ];

    //任务类型
    const TYPE_GOODS = 'goods';//商品
    const TYPE_DELIVER = 'deliver';//发货
    const TYPE_CONFIRM = 'confirm';//确认收货
    const TYPE_RENTAL = 'rental';//订单履约
    const TYPE_INSURANCE = 'insurance';//订单投保
    const TYPE_INSURANCE_REFUND = 'insurance_refund';//订单退保

    const INSURANCE_TYPE_RB = 'RJPYGNCN'; //杭州⼈保
    const INSURANCE_TYPE_YT = 'JWBCQILO'; //亚太保险

    /**
     * 上链任务
     * @param $id
     * @param $type
     * @param string $params
     * @return bool
     */
    public static function toTask($id,$type,$params=''){
        if($id && $type && in_array($type,[
                self::TYPE_CONFIRM,
                self::TYPE_DELIVER,
                // self::TYPE_GOODS,
                self::TYPE_RENTAL,
            ]) && is_array($id)
        ){
            if($type == self::TYPE_DELIVER || $type == self::TYPE_CONFIRM){
                $order = Order::where(['trade_no'=>$id[0]])->select('pay_type','financing_type')->first();
                $order = obToArray($order);
                if(!$order){
                    return false;
                }
                if($order['pay_type'] == Order::ORDER_PAY_TYPE_HUABEI){
                    return false;
                }
            }

            if($type == self::TYPE_RENTAL){
                $order_id = OrderLease::where(['id'=>$id[0]])->value('order_id');
                // $order = Order::where(['id'=>$order_id,'financing_type'=>Order::FINANCING_TYPE_RONG])->select('pay_type','financing_type')->first();
                $order = Order::where(['id'=>$order_id])->select('pay_type','financing_type')->first();
                $order = obToArray($order);
                if(!$order){
                    return false;
                }
                if($order['pay_type'] == Order::ORDER_PAY_TYPE_HUABEI){
                    return false;
                }
                if(!$params){
                    $params = self::LEASE_RENT_STATUS_YES; //默认足额归还
                }
            }
            $data = [
                'ids'=>json_encode($id),
                'type'=>$type,
                'params'=>$params,
                'create_time'=>dateFormat(time()),
            ];
            //添加数据
            $taskId = ZlbNotoryTask::insertGetId($data);
            if($taskId){
                self::requestLog('租赁宝上链任务添加成功',$data,['task_id'=>$taskId]);
                return true;
            }else{
                self::requestLog('租赁宝上链任务添加失败',[$id,$type,$params]);
            }
        }
        return false;
    }

    /**
     * 请求数据格式化
     * @param $res
     * @return array
     */
    public static function format($res){
        if(isset($res['result_msg']) && $res['result_msg'] == 'success' && $res['code'] == 0 && $res['result_code'] == 200){
            //成功
            return ['tx_hash'=>isset($res['response_data']) ? $res['response_data'] : '','status'=>1];
        }else{
            //失败
            return ['tx_hash'=>isset($res['response_data']) ? $res['response_data'] : '','status'=>0];
        }
    }

    /**
     * 租赁宝类型转换
     * @param $zlbClass
     * @return array\
     */
    public static function categoryClass($zlbClass){
        $mainClass = '';
        $subClass = '';
        if($zlbClass){
            $class = explode('_',$zlbClass);
            if(isset($class[0])){
                $mainClass = strtoupper($class[0]);//一级行业
                $subClass = $zlbClass;//二级行业
            }
        }
        if(!$zlbClass || !$mainClass || !$subClass){
            $class = explode('_',self::DEFAULT_CATEGORY_CLASS);
            $mainClass = strtoupper($class[0]);//一级行业
            $subClass = self::DEFAULT_CATEGORY_CLASS;//二级行业
        }
        return ['mainClass'=>$mainClass,'subClass'=>$subClass];
    }



    /**
     * log
     * @param $message
     * @param array $request
     * @param array $response
     */
    public static function requestLog($message,$request=[],$response=[]){
        $content = [
            'request'=>is_object($request) ? object_array($request) : $request,
            'response'=>is_object($response) ? object_array($response) : $response,
        ];
        \Illuminate\Support\Facades\Log::debug($message,$content);
    }

    /**
     * 参数组装记录
     * @param $request
     * @param $notary
     * @return false|string
     */
    public static function paramsResponse($request,$notary){
        return json_encode([
            'request'=> ["biz_content" => json_encode($request)],
            'response'=>is_object($notary) ? object_array($notary) : $notary,
        ]);
    }

    /**
     * 租赁宝请求入口
     * @param $param
     * @param string $type
     * @param string $method
     * @return mixed
     * @throws \AntCloudSDKCore\Exception\ClientException
     */
    public function getAntCloudClient($param,$type='',$method=''){
        if(!empty($type)){
            $request = [
                "biz_content" => json_encode($param),
                "type" => $type,
                "method" => empty($method) ? self::PRODUCT_METHOD : $method,
                "version" => self::VERSION_NO,
                "product_instance_id" => 'notary-api-prod',
                "region_name" => self::REGINON_NAME,
            ];
        }else{
            $request = array_merge([
                "method" => empty($method) ? self::PRODUCT_METHOD : $method,
                "version" => self::VERSION_NO,
                "product_instance_id" => 'notary-api-prod',
                "region_name" => self::REGINON_NAME,
            ],$param);
        }
// dd($request);
        // 发送调用请求，解析响应结果
        $res = AlipayBaseService::getAntCloudClient()->execute($request);
        // dd($res);
        self::requestLog('租赁宝接口入参结果',$request,$res);
        // dd(111);
        return  $res ;
    }

    /**
     * 租赁宝购买保险请求入口
     * @param $param
     * @param $type
     * @param $method
     * @return mixed
     * @throws \AntCloudSDKCore\Exception\ClientException
     */
    public function getInsuranceClient($param,$type,$method){
        $request = [
            "biz_content" => json_encode($param),
            "type" => $type,
            "operation_type" => "INSERT",
            "method" => $method,
            "version" => self::VERSION_NO,
            "product_instance_id" => 'notary-api-prod',
            "region_name" => self::REGINON_NAME,
        ];
        // 发送调用请求，解析响应结果
        $res = AlipayBaseService::getAntCloudClient()->execute($request);
        self::requestLog('租赁宝保险入参结果',$request,$res);
        return  $res ;
    }


    /**
     * 存证⽂件哈希
     * @return mixed
     */
    public function fileApi($param)
    {
        $request = [
            'hash'=> $param['hash'],//文件hash
            'leaseCorpId'=>'91330381MAC65FWH5X',//租赁机构统⼀社会信⽤码
            'leaseCorpName'=>'瑞安市诺明网络科技有限公司',//租赁机构名称
            'leaseCorpOwnerName'=>'吴力军',//租赁机构法⼈姓名
        ];
        $res = $this->getAntCloudClient($request,'',self::FILE_METHOD);
        if(isset($res['result_msg']) && $res['result_msg'] == 'success' && $res['code'] == 0 && $res['result_code'] == 200){
            //成功
            self::requestLog('上传文件成功',$request,$res);
            return true;
        }else{
            //失败
            self::requestLog('上传文件错误',$request,$res);
            return false;
        }
    }


    /**
     * 租赁宝商品信息
     * @return mixed
     */
    public function productApi($param)
    {
        $class = self::categoryClass($param["categoryCass"]);
        $request = [
            "supplierName"=>'瑞安市诺明网络科技有限公司',//供应商模式则为供应商，否则平台⾃⼰
            "supplierId"=>'XMAUNLUF',//供应商id
            "productOrigin"=>2,//商品来源，1供应商 2表示租赁机构
            "installPrice"=>0,//安装服务费
            "productName"=>$param["productName"],//商品名称
            "productModel"=>$param["productModel"],//商品规格
            "mainClass"=>$class['mainClass'],//⼀级行业
            "subClass"=>$class['subClass'],//二级行业
            "productId"=>$param["productId"],//商品编码
            "estimatedShipment"=>$param['estimatedShipment'],//预估出货量
            "productDetailInfo"=>$param["productDetailInfo"],//商品详情
            "productBrand"=>$param["productBrand"],//商品品牌
            "productVersion"=>$param["productVersion"],//商品版本
            "realStock"=>$param["realStock"],//实际库存量
            "productUrl"=>$param["productUrl"],//商品链接
            "depositPrice"=>toHao($param["depositPrice"]),//免押金额，精确到毫厘，即123400表示12.34元
            "productPrice"=>toHao($param["productPrice"])//商品价格，精确到毫厘，即123400表示12.34元
        ];
        return $this->getAntCloudClient($request,self::API_TYPE_PRODUCT);
    }

    /**
     * 租赁宝订单⽤户信息
     * @return mixed
     */
    public function userApi($param)
    {
        $request = [
            "leaseCorpId" => '91330381MAC65FWH5X',//营业执照号
            "leaseCorpName" => '瑞安市诺明网络科技有限公司',//公司名称
            "leaseCorpOwnerName" => '吴力军',//公司法人
            "userType" => "1",//身份认证类型 1⽀付宝实⼈，2芝麻实⼈，3⾮蚂蚁实⼈
            "lesseeType" => "2",//租赁⽅类别1.企业⽤户 2.个⼈⽤户
            "loginType" => "2",//⽤户登录名类型 1.商户会员2.⽀付宝3.其他
            "alipayUID" => $param['loginId'],//阿里user_id
            "loginTime" => $param['loginTime'],// 登录时间 date('Y-m-d H:i:s')
            "loginId" => $param['loginId'],// 支付宝登录名
            "orderId" => $param['orderId'],//平台订单号
            "userId" => '330381198507130013',//承租人身份证号码
            "userImageHash" => $param['userImageHash'],//承租⼈身份证照⽚正⾯哈希
            "userBlockchainVerifyHash" => $param['certifyId'],//区块链认证Hash，若为支付宝实人，必填
            "userName" => $param['userName'],//承租人姓名
            "userPhoneNumber" => $param['userPhone'],//承租人电话
            "userImageUrl" => md5($param['userImageUrl']),//租赁⼈身份证照⽚正⾯地址【租赁 机构⾃⾏加密】
        ];
        return $this->getAntCloudClient($request,self::API_TYPE_USER);
    }

    /**
     * 租赁宝订单信息
     * @return mixed
     */
    public function orderApi($param)
    {
        $code = AddressClient::getArea($param['province'],$param['city'],$param['area']);
        $request = [
            "dueMode" => 2,//到期形式：1 到期买断 2到期归还
            "storeType" => 1,//1.实体仓 2.虚拟仓
            "orderPayType" => $param['orderPayType'],//订单⽀付类型 1 预授权，2信⽤套餐，3⽀付宝代扣，4其他
            "provinceCode" => $code['provinceCode'],//承租人省份编码
            "cityCode" => $code['cityCode'],//承租人城市编码
            "districtCode" => $code['areaCode'],//承租人地区编码
            "acutalPreAuthFree" => toHao($param['creditAmount']),//芝麻信用免押金额 实际预授权⾦额，芝麻 信⽤免押⾦额 精确到毫 厘，即123400表示 12.34元
            "depositFree" => toHao($param['orderCreditRent']),//免押金额 精确到毫厘，即123400表示12.34元
            "buyOutPrice" => toHao($param['buyMoney']),//到期买断价 精确到毫厘，即123400表示12.34元
            "totalRentMoney" => toHao($param['orderTotalRent']),//租⾦总额,精确到毫厘， 即123400表示12.34元
            "rentPricePerMonth" => toHao($param['monthAmount']),//月租金 精确到毫厘，即123400表示12.34元
            "leaseServiceFileHash" => $param['contentHash'],//融资租赁及服务协议文件hash
            "orderCreateTime" => $param['orderCreateTime'],//订单创建时间 格式为2019-8-31 12:00:00
            "orderId" => $param['orderId'],//订单id 长度不可超过50
            "orderPayId" => $param['orderStagesId'],//⽀付订单ID
            "orderPayTime" => $param['payTime'],//订单支付时间 格式为2019-8-31 12:00:00
            "leaseContractUrl" => $param['leaseContractUrl'],//租赁合同地址
            "rentTerm" => $param['monthTotal'],//租期/月
            "userAddress" => $param['userAddress'],//承租人收货地址
            "yidunScore" => intval($param['yidunScore']),//蚁盾分数

        ];
        return $this->getAntCloudClient($request,self::API_TYPE_ORDER);
    }

    /**
     * 租赁宝订单商品信息
     * @return mixed
     */
    public function orderProductApi($param)
    {
        $serialNumber = [];
        for($i=1;$i<=$param['number'];$i++){
            $serialNumber[] = $param['serialNumber'];
        }

        $request = [
            "productInfo"=>[
                [
                    'supplierId'=>'XMAUNLUF',//供应商的⾦融科技租户 id
                    'productNumber'=>$param['number'],//产品数量
                    'productImeiId'=>implode(',',$serialNumber),//供应商对应的产品唯⼀ 标识码
                    'productId'=>$param['productId'],//商品编码，与融资租赁 公司约定的产品Id，⻓ 度不超过50
                    'productName'=>$param['productName'],//产品名称，⻓ 度不超过50
                    'productVersion'=>$param['productVersion'],//商品版本
                    'productPrice'=>toHao($param['productPrice']),//商品价格，精确到毫厘，即123400表示12.34元
                ]
            ],//产品信息，不超过100 个
            "orderId"=>$param['orderId'],//订单id ⻓度不可超过 50
            "leaseId"=>'XMAUNLUF',//租赁机构租户id
        ];
        return $this->getAntCloudClient($request,self::API_TYPE_ORDER_PRODUCT);
    }

    /**
     * 租赁宝物流信息-已发货
     * @return mixed
     */
    public function logisticDeliverApi($param)
    {
        $request = [
            "logisticStatus"=>1,//物流状态,1 已发货 2运 输中 3已签收 0其他
            "leaseStatus"=>1,//是否退租，1为租赁 2为退租
            "leaseId"=>'XMAUNLUF',//租赁机构租户id
            "logisticCompanyName"=>$param['logisticCompanyName'],//物流公司简称
            "logisticsOrderId"=>$param['logisticsOrderId'],//物流订单id
            "deliverTime"=>$param['deliverTime'],//物流发货时间,格式为 2019-8-31 12:00:00
            "orderId"=>$param['orderId'],//订单id ⻓度不可超过 50
            "arriveConfirmHash"=>$param['arriveConfirmHash'],//存证
            "arriveConfirmUrl"=>$param['arriveConfirmUrl'],//记录URL
        ];
        return $this->getAntCloudClient($request,self::API_TYPE_ORDER_LOGISTIC);
    }

    // 物流信息-已签收
    public function logisticConfirmApi($param)
    {
        $request = [
            "logisticStatus"=>3,//物流状态,1 已发货 2运 输中 3已签收 0其他
            "leaseStatus"=>1,//是否退租，1为租赁 2为退租
            "leaseId"=>'XMAUNLUF',//租赁机构租户id
            "logisticCompanyName"=>$param['logisticCompanyName'],//物流公司简称
            "logisticsOrderId"=>$param['logisticsOrderId'],//物流订单id
            "deliverTime"=>$param['deliverTime'],//物流发货时间,格式为 2019-8-31 12:00:00
            "orderId"=>$param['orderId'],//订单id ⻓度不可超过 50
            "arriveConfirmHash"=>$param['arriveConfirmHash'],//存证
            "arriveConfirmTime"=>$param['arriveConfirmTime'],//⽤户签收时间，格式为 2019-8-31 12:00:00，已签收需要必填
            "arriveConfirmUrl"=>$param['arriveConfirmUrl'],//签收记录URL，已签收需要必须
            "extraInfo"=>$param['extraInfo'],//资⽅定义的其他额外字段，以json形式传递
        ];
        return $this->getAntCloudClient($request,self::API_TYPE_ORDER_LOGISTIC);
    }

    /**
     * 租赁宝承诺信息
     * @return mixed
     */
    public function leasePromiseApi($param)
    {
        $request = [
            "leaseAlipayUid" => config('alipay.alipayUID'),//租赁公司⽀付宝UID
            "limit" => self::LEASE_LIMIT_DAY * 86400 * 1000,//宽限期，精确到毫秒
            "orderId" => $param['orderId'],//订单id，长度不可超过50
            "payDateList" => $param['payDateList'],////应付租⾦时间，格式为 2019-8-31 12:00:00
            "payPeriod" => $param['payPeriod'],//总租期
            "payMoneyList" => $param['payMoneyList']//应付租⾦，精确到毫 厘，即123400表示 12.34元
        ];
        return $this->getAntCloudClient($request, self::API_TYPE_ORDER_LEASE_PROMISE);
    }


    /**
     * 租赁宝订单履约信息
     * @return mixed
     */
    public function rentalApi($param)
    {
        $request = [
            "returnWay"=>$param['returnWay'],//归还方式，1预授权代扣，2支付宝代扣，3主动还款，4其他
            "returnVoucherType"=>1,//还款凭证类型，1支付宝，2平台代收(客户主动还款)，3其他
            "rentalReturnState"=>$param['rentalReturnState'],//租金归还状态，1足额归还，2部分归还，3未归还，4退租，5该订单整个生命周期已完结
            "charge"=>toHao(toServiceCharge($param['rentalMoney'])),//手续费，如通过预授权，代扣的方式规划，必填
            "orderId"=>$param['orderId'],//订单id，长度不可超过50
            "rentalMoney"=>toHao($param['rentalMoney']),//租金归还金额，精确到毫厘，即123400表示，12.34元
            "remainTerm"=>$param['remainTerm'],//剩余归还期数
            "returnTime"=>$param['returnTime'],//归还时间，格式为”2019-07-31 12:00:00’
            "returnVoucherSerial"=>$param['returnVoucherSerial'],//还款凭证编号，不超过128字符，支付宝流水号
            "leaseTermIndex"=>$param['leaseTermIndex']//租期编号
        ];
        // dd($request);
        return $this->getAntCloudClient($request,self::API_TYPE_ORDER_RENTAL);
    }


    //租赁宝商品信息查询接口
    public function queryProductApi(){
        $request = [
            'orderId' => '',
        ];
        $res = $this->getAntCloudClient($request,self::API_TYPE_ORDER,self::PRODUCT_QUERY_METHOD);
        return $res;
    }

    //租赁宝保险创建接口
    public function insuranceCreateApi($param){
        $request = [
            'orderId'=>$param['orderNo'],
            'insuredIdNo'=>$param['insured']['insuredIdNo'],//被保人统⼀社会信⽤码
            'insuranceCorpIsvAccount'=>self::INSURANCE_TYPE_RB,
            "insured"=>$param['insured'],
            "holder"=>[
                "holderIdNo"=>config('alipay.antchain.leaseCorpId'),
                "holderName"=>config('alipay.antchain.leaseCorpName'),
                "holderMobile"=>config('alipay.antchain.leasePhone'),
                "holderAddress"=>config('alipay.antchain.leaseAddress'),
                "holderMail"=>config('alipay.antchain.leasEmail'),
            ],
        ];
        return $this->getInsuranceClient($request,self::API_TYPE_INSURANCE,self::PRODUCT_METHOD);
    }

    //租赁宝保险退保接口
    public function insuranceRefundApi($param){
        $request = [
            'orderId'=>$param['orderId'],
            'isvAccount'=>'XMAUNLUF',//供应商的⾦融科技租户 id,
            'methodType'=>1,//⽅法类型 0投保、1退保
            'insuredIdNo'=>$param['insuredIdNo'],
            'insuranceCorpIsvAccount'=>self::INSURANCE_TYPE_RB,
        ];
        return $this->getInsuranceClient($request,self::API_TYPE_INSURANCE,self::PRODUCT_METHOD);
    }

    //租赁宝保险查询接口
    public function insuranceQueryApi($param){
        $request = [
            'orderId'=>$param['orderId'],
        ];
        return $this->getInsuranceClient($request,self::API_TYPE_INSURANCE,self::PRODUCT_QUERY_METHOD);
    }

}
